import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { User } from "./models/user.entity";
import { DeepPartial, Repository } from "typeorm";
// import { UserType } from "./dto/user.type";
// Repository是一个提供数据库操作的工具库
@Injectable()
export class UserService {
    // 注入User实体
    constructor(
        @InjectRepository(User) private UserRepository: Repository<User>
    ) { }
    // 返回值是promise对象
    // DeepPartial是一个将实体（USER）内部的所有属性加上?，即可以省略
    async create(entity: DeepPartial<User>): Promise<boolean> {
        const res = await this.UserRepository.insert(entity);
        // console.log('res', res);
        if (res && res.raw.affectedRows > 0) {
            return true
        }
        return false;
    }

    // 删除用户
    async del(id: string): Promise<boolean> {
        const res = await this.UserRepository.delete(id);
        // console.log('res', res);
        if (res && res.affected && res.affected > 0) {
            return true;
        }
        return false;
    }
    // 修改用户
    async update(id: string, entity: DeepPartial<User>): Promise<boolean> {
        const res = await this.UserRepository.update(id, entity);
        // console.log('res', res);
        if (res && res.affected && res.affected > 0) {
            return true;
        }
        return false;
    }
    // 查询用户
    async findById(id: string): Promise<User | null> {
        const res = await this.UserRepository.findOne({
            where: {
                id: id,
                // ...entity
            }
        });
        // console.log('res', res);
        return res;
    }
    // 通过手机查询用户
    async findByTel(tel: string): Promise<User | null> {
        const res = await this.UserRepository.findOne({
            where: {
                tel: tel,
                // ...entity
            }
        });
        // console.log('res', res);
        return res;
    }
    // 修改用户的验证码
    async updateCode(id: string, code: string): Promise<boolean> {
        const res = await this.UserRepository.update(id, {code,codeCreateTimeAt:new Date()});
        // console.log('res', res);
        if (res && res.affected && res.affected > 0) {
            return true;
        }
        return false;
    }
}